const {
	list,
	rsp,
	parseData,
	paresPostData
} = require('../utils.js');
const Router = require('koa-router');
const router = new Router();




//====================================================================================
//获取班级学生数组
function getStudents(classId, callback) {
	if (classId) {
		//找到班级
		const cs = list[classId - 1];
		//找到班级下的学生
		cs.students.forEach(stu => {
			//动态的更新学生的班级信息
			stu.className = cs.className;
			stu.classType = cs.classType;
		})
		callback && callback(cs);
		return cs.students;
	} else {
		throw new Error('检测到classId不存在')
	}
}
//====================================================================================
//获取班级列表数据
router.get('/list', (ctx, next) => {
	//获取筛选参数
	const { field, value, page = 1, limit = 10, classId } = ctx.request.query;
	let students = null;
	let classData = {};
	try {
		students = getStudents(classId, cs => {
			classData.classId = classId;
			classData.className = cs.className;
			classData.classType = cs.classType;
		});
	} catch (e) {
		return ctx.body = rsp(null, '检测到classId不存在', 10001)
	}
	// ======================================
	let result = null;
	//匹配条件筛选项
	if (field && value) {
		result = students.filter(stu => {
			//转化为字符串
			let val = stu[field].toString();
			//判断包含关系
			return val.includes(value)
		})
	} else {
		result = students;
	}
	//再匹配页码条件
	const total = result.length;
	result = result.slice((page - 1) * limit, page * limit);
	ctx.body = rsp({
		list: result,
		//当前页码
		page,
		limit,
		//总共查询到的条数
		total,
		classData
	})
})
//编辑或新增班级数据
router.post('/set', async (ctx, next) => {
	let { id, classId, ...param } = await paresPostData(ctx);
	//找到班级下的所有学生
	let students = null;
	try {
		students = getStudents(classId);
	} catch (e) {
		return ctx.body = rsp(null, '检测到classId不存在', 10001)
	}

	let msg = '';
	if (id) {
		//如果id存在，则为修改操作
		//根据ID找到该班级
		let stu = students.find(stu => stu.id === Number(id));
		Object.assign(stu, param);
		msg = '编辑成功';
	} else {
		//如果id不存在，则为新增操作
		//构造新的id,需要找到班级最大的id
		let id = 0;
		students.forEach(stu => {
			if (id < stu.id) id = stu.id;
		})
		//对新增的班级编号
		param.id = id + 1;
		//开班
		students.push(param);
		msg = '新增成功';
	}
	//操作成功的响应
	ctx.body = rsp({}, msg);
})
//删除班级数据
router.get('/delete', (ctx, next) => {
	const { id, classId } = ctx.request.query;
	//找到班级下的所有学生
	let students = null;
	try {
		students = getStudents(classId);
	} catch (e) {
		return ctx.body = rsp(null, '检测到classId不存在', 10001)
	}
	if (id) {
		//找到班级的下标
		let index = students.findIndex(stu => stu.id === Number(id));
		//删除对应的班级
		students.splice(index, 1)
		//操作成功的响应
		ctx.body = rsp();
	}
})



//====================================================================================
module.exports = router.routes()
